﻿window.onload = function () {
	getPic();
	moreGetPic();
	document.body.addEventListener('mouseover', clear, false);
	document.body.addEventListener('mouseout', moreGetPic, false);
	window.onload = null;
}

function moreGetPic() {
	clear();
	window.timeout = setTimeout(function () {
			getPic();
			moreGetPic();
		}, 3000);
}

function clear() {
	clearTimeout(window.timeout);
	delete window.timeout;
}

function getPic() {
	var key = "美女",
	showPics = 24;
	var url = "http://image.baidu.com/i?tn=resultjsonavatarnew&ie=utf-8&cg=girl&pn=" + Math.floor(Math.random() * 300) + "&rn=100&z=&fr=&width=&height=&lm=-1&ic=0&s=0&word=" + encodeURIComponent(key);
	ajax(url, function (msg) {
		var obj = JSON.parse(msg);
		if (obj && obj.imgs && obj.imgs.length) {
			var iArr = [],
			index;
			Array.prototype.slice.call(document.body.getElementsByTagName("img"), 0).forEach(function (e) {
				e.remove()
			});
			for (var i = 0; i < showPics; i++) {
				var img = document.createElement("img");
				while (iArr.indexOf(index) !== -1 || index === undefined) {
					index = Math.floor(Math.random() * obj.imgs.length);
				}
				iArr.push(index);
				img.src = obj.imgs[index].thumbURL;
				document.body.appendChild(img);
			}
		}
	});
}

function ajax(url, callback) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			callback(xmlhttp.responseText);
		}
	}
	xmlhttp.open("POST", url, false);
	xmlhttp.send();
}
